<?php

namespace app\api\controller;

use app\admin\model\Pickuppoint as PickuppointMdl;

class Pickuppoint extends Base
{

    /**
     * 获取自提点列表
     */
    public function getList()
    {
        $param = self::getHttpParam();

        if (empty($param->lng)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '经度(lng) 不能为空');
        }
        if (empty($param->lat)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '纬度(lat) 不能为空');
        }

        $lng = $param->lng;
        $lat = $param->lat;
        $where = [
            'status' => 1,
        ];

        $model = new PickuppointMdl();
        $fields = 'id, name, person, phone, region, address, address_geo, business_start_time, business_end_time';
        $order = 'create_date DESC';
        $list = $model->where($where)->field($fields)->order($order)->select();
        if(!$list){
            return show(config('status.ERROR_STATUS'), '没有自提点', '没有自提点');
        }

        // 自提点 按由近到远排序
        $datas = [];
        foreach ($list as $item) {
            $distance = $this->getDistance($lat, $lng, $item);
            if (!empty($distance)) {
                $item['distance'] = $distance;
                $datas[] = $item;
            }
        }

        foreach ($datas as $k => $v) {
            $dos[$k] = $v['distance'];
        }
        // 进行排序
        array_multisort($dos, SORT_ASC, $datas);

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $datas);
    }

    /**
     * 根据经纬度获得与自提点间的距离,保留两位小数
     */
    protected function getDistance($lat, $lng, $data)
    {
        $site = explode(",", $data['address_geo']);

        // 将角度转为狐度
        $radLat1 = deg2rad($lat); //deg2rad()函数将角度转换为弧度
        $radLat2 = deg2rad($site[0]);
        $radLng1 = deg2rad($lng);
        $radLng2 = deg2rad($site[1]);

        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;

        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6371.393 * 1000;

        return sprintf("%.2f", $s);
    }
}